package com.yunban.project.aspect;

import com.yunban.project.annotation.ServiceSwitch;
import com.yunban.project.exception.BaseException;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;

import javax.annotation.Resource;

/**
 * @author lijiajun
 * @date 2024/3/20
 */
@Slf4j
@Aspect
@Component
@RequiredArgsConstructor
public class ProgramSwitchAspect {


    private final RedisTemplate<String, String> redisTemplate;

    private final static String SWITCH_KEY = "switch:";

    @Pointcut("@annotation(com.yunban.project.annotation.ServiceSwitch)")
    public void servicePointcut() {
    }

    @Around("servicePointcut() && @annotation(serviceSwitch)")
    public Object around(ProceedingJoinPoint joinPoint, ServiceSwitch serviceSwitch) throws Throwable {
        int closeValue = serviceSwitch.closeValue();
        String message = serviceSwitch.message();
        log.info("服务开关状态:{}, 消息:{}", closeValue, message);
        // 根据开关状态和消息进行相应的处理逻辑
        // 从缓存里拿服务是否开启
        String s = this.redisTemplate.opsForValue().get(SWITCH_KEY);
        if (!StringUtils.hasText(s)) {
            // 加一个
            redisTemplate.opsForValue().set(SWITCH_KEY, String.valueOf(closeValue));
            s = String.valueOf(closeValue);
        }
        if (Integer.parseInt(s) == closeValue) {
            throw new BaseException(message);
        }
        return joinPoint.proceed();
    }
}
